package com.ruoyi.xqsp.controller;


import java.math.BigDecimal;
import java.util.*;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.quyang.voice.model.ConsumeRecord;
import com.quyang.voice.service.ClientConfigService;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.status.ResponseUtil;
import com.ruoyi.xqsp.domain.*;
import com.ruoyi.xqsp.domain.entity.User;
import com.ruoyi.xqsp.service.*;

import com.ruoyi.xqsp.utils.TokenServices;
import com.ruoyi.xqsp.utils.XqidUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;

import org.springframework.security.crypto.password.PasswordEncoder;
//import org.springframework.util.*;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

import static com.ruoyi.xqsp.controller.PhoneController.requestData;

/**
 * 用户表Controller
 *
 * @author ruoyi
 * @date 2021-04-26
 */
@Api(value = "用户管理", tags = "用户管理")
@RestController
@RequestMapping("/xqsp/users")
public class SpUsersController extends BaseController {
    @Autowired
    private ISpUsersService spUsersService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISpVideoCategoryService spVideoCategoryService;
    @Autowired
    private ISpRechargeRecordService spRechargeRecordService;
    @Autowired
    private ISpHeadImgService spHeadImgService;

//    @Autowired
//    CustAccountbaseService custAccountbaseService;

    private Random random = new Random();

    @Autowired
    private TokenServices tokenService;

    @Autowired
    ClientConfigService configService;

    @Autowired
    UserPhoneService uploadPhone;

    @Autowired
    SpConsumeRecordService consumeRecordService;
    /**
     * 查询用户表列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpUsers spUsers) {
        startPage();
        List<SpUsers> list = spUsersService.selectSpUsersList(spUsers);
        return getDataTable(list);
    }


    /**
     * 根据xqid查询用户的下级用户
     */

    @ApiOperation("根据xqid查询用户的下级用户")
    @GetMapping("/userXqid/{userXqid}")
    public TableDataInfo lookList(@PathVariable("userXqid") String userXqid) {
        startPage();
        List<SpUsers> list = spUsersService.selectSpUsersListByXqid(userXqid);
        return getDataTable(list);
    }
    /**
     * 根据xqid查询用户的下级用户
     */
    @ApiOperation("根据xqid查询用户的下级用户")
    @GetMapping("/userXqid/")
    public ResponseUtil lookList(HttpServletRequest request) {
        SpUsers loginUser = tokenService.getLoginUser(request);

        QueryWrapper wrapper1 = new QueryWrapper();

        wrapper1.eq("type",5);
        wrapper1.eq("user_id",loginUser.getUserId());
        wrapper1.select("IFNULL(SUM(money),0) as vipDay");
        Map map1 = consumeRecordService.getMap(wrapper1);



        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_promote_code",loginUser.getUserXqid());
        int count = spUsersService.count(wrapper);
        HashMap map = new HashMap();
        map.put("count",count);
        map.put("time",loginUser.getUserMembersDay());
        map.put("vipDay",Long.valueOf(map1.get("vipDay").toString()));



//        List<SpUsers> list = spUsersService.selectSpUsersListByXqid(loginUser.getUserXqid());


        return ResponseUtil.success(map);
    }


    /**
     * 查询日新增
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:list')")
    @GetMapping("/list/userCountDay")
    public TableDataInfo userCountDay(SpUsers spUsers) {
        startPage();


        spUsers.setUserTime(new Date());
        List<SpUsers> list = spUsersService.selectSpUsersList(spUsers);
        return getDataTable(list);
    }

    /**
     * 查询月新增
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:list')")
    @GetMapping("/list/userCountMonth")
    public TableDataInfo userCountMonth(SpUsers spUsers) {
        startPage();

        spUsers.setUserTime(new Date());
        List<SpUsers> list = spUsersService.selectSpUsersListMonth(spUsers);
        return getDataTable(list);
    }

    /**
     * 查询日活
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:list')")
    @GetMapping("/list/userOnlineCountDay")
    public Integer userOnlineCountDay(SpUsers spUsers) {
        Integer size = redisCache.getCacheList("userDay").size();
        return size;
    }

    /**
     * 查询月活
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:list')")
    @GetMapping("/list/userOnlineCountMonth")
    public Integer userOnlineCountMonth(SpUsers spUsers) {
        Integer size = redisCache.getCacheObject("monthDay");
        return size;
    }


    /**
     * 查询在线人数
     */
    @GetMapping("/list/userOnlineCount")
    public Integer userOnlineCount() {
        QueryWrapper<SpUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_login_state", 1);
        return spUsersService.count(queryWrapper);
    }


    /**
     * 导出用户表列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:export')")
    @Log(title = "用户表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpUsers spUsers) {
        List<SpUsers> list = spUsersService.selectSpUsersList(spUsers);
        ExcelUtil<SpUsers> util = new ExcelUtil<SpUsers>(SpUsers.class);
        return util.exportExcel(list, "users");
    }

    /**
     * 获取用户表详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return AjaxResult.success(spUsersService.selectSpUsersById(userId));
    }

    /**
     * 新增用户表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:add')")
    @Log(title = "用户表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpUsers spUsers) {
        String xqid = XqidUtils.UserXqid();
        if (spUsersService.selectSpUsersByXqId(xqid) == null) {
            spUsers.setUserXqid(xqid);
        } else {
            add(spUsers);
        }

        return toAjax(spUsersService.insertSpUsers(spUsers));
    }

    /**
     * 修改用户表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:edit')")
    @Log(title = "用户表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpUsers spUsers) {
        return toAjax(spUsersService.updateSpUsers(spUsers));
    }


    /**
     * 会员充值
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:edit')")
    @Log(title = "用户表", businessType = BusinessType.UPDATE)
    @PutMapping("/updateUsersMg")
    public AjaxResult updateUsersMg(@RequestBody User spUsers) {
        if (spUsers.getUserMembersDay() == null) {
            spUsers.setUserMembersDay(new Date());
        }

        SpRechargeRecord spRechargeRecord = new SpRechargeRecord();
        spRechargeRecord.setRechargeRecordTime(new Date());

        spRechargeRecord.setRechargeRecordMoney(spUsers.getUserMoney());
        spRechargeRecord.setRechargeRecordType(9);
        spRechargeRecord.setRechargeRecordState(1);
        spRechargeRecord.setUserId(spUsers.getUserId());

        String rechargeRecordOrder;

        boolean bHave = true;
        while (bHave) {
            rechargeRecordOrder = XqidUtils.UserRecord();
            if (spRechargeRecordService.selectSpRechargeRecordByOrder(rechargeRecordOrder) == null) {
                bHave = false;
                spRechargeRecord.setRechargeRecordOrder(rechargeRecordOrder);
            }
        }
        spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord);

        SpUsers rechargeUser = spUsersService.selectSpUsersById(spUsers.getUserId());
        if (rechargeUser != null) {
            if (rechargeUser.getUserVipType() < spUsers.getUserVipType())
                rechargeUser.setUserVipType(spUsers.getUserVipType());
            spUsersService.updateSpUsers(rechargeUser);
        }

        SpUsers spUsers1 = new SpUsers();
        spUsers1.setUserMembersDay(spUsers.getUserMembersDay());
        spUsers1.setUserGlod(spUsers.getUserGlod());
        spUsers1.setUserId(spUsers.getUserId());
        return toAjax(spUsersService.updateSpUsersMg(spUsers1));
    }

    /**
     * 充值
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:edit')")
    @Log(title = "用户表", businessType = BusinessType.UPDATE)
    @PutMapping("/updateUsersGlod")
    public AjaxResult updateUsersGlod(@RequestBody User spUsers) {
        if (spUsers.getUserGlod() == null) {
            spUsers.setUserGlod(BigDecimal.ZERO);
        }

        SpRechargeRecord spRechargeRecord = new SpRechargeRecord();
        spRechargeRecord.setRechargeRecordTime(new Date());
//        spRechargeRecord.setRechargeRecordWay(2l);
        spRechargeRecord.setRechargeRecordMoney(spUsers.getUserMoney());
        spRechargeRecord.setRechargeRecordType(7);
        spRechargeRecord.setRechargeRecordState(1);
        spRechargeRecord.setUserId(spUsers.getUserId());

        String rechargeRecordOrder;

        boolean bHave = true;
        while (bHave) {
            rechargeRecordOrder = XqidUtils.UserRecord();
            if (spRechargeRecordService.selectSpRechargeRecordByOrder(rechargeRecordOrder) == null) {
                bHave = false;
                spRechargeRecord.setRechargeRecordOrder(rechargeRecordOrder);
            }
        }
        spRechargeRecordService.insertSpRechargeRecord(spRechargeRecord);
        SpUsers spUsers1 = new SpUsers();
        spUsers1.setUserGlod(spUsers.getUserGlod());
        spUsers1.setUserId(spUsers.getUserId());
        return toAjax(spUsersService.updateSpUsersMg(spUsers1));
    }

    /**
     * 删除用户表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:users:remove')")
    @Log(title = "用户表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(spUsersService.deleteSpUsersByIds(userIds));
    }

    /**
     * 用户登录
     *
     * @param userLoginReq
     * @return
     */
    List<SpUsers> userLoginReqSet = new ArrayList<>();

    @Autowired
    PasswordEncoder passwordEncoder;


    @Autowired
    AuthenticationManagerBuilder authenticationManagerBuilder;

    @Autowired


    ToolLocalStorageService toolLocalStorageService;


    @ApiOperation("登录")
    @PostMapping("/login")
    @CrossOrigin
    public ResponseUtil userLogin(@RequestBody UserLoginReq userLoginReq) {


        Map<String, Object> map = new HashMap<>();
        QueryWrapper<SpUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone", userLoginReq.getUserPhone());
        SpUsers users = spUsersService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(users)){
            return ResponseUtil.fail("账户不存在");
        }else {
            if (! passwordEncoder.matches(userLoginReq.getUserPassword(),users.getUserPassword())){
             return ResponseUtil.fail("密码错误");
            }
        }
        UUID uuid = UUID.randomUUID();
        users.setToken(uuid.toString().replace("-",""));
        String cacheObject = redisCache.getCacheObject((Constants.LOGIN_USERNAME_KEY + userLoginReq.getUserPhone()), String.class);
//        if (! StringUtils.isEmpty(cacheObject)){
//            redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY+cacheObject);
//        }


        redisCache.setCacheObject(Constants.LOGIN_TOKEN_KEY+users.getToken(),users,Constants.TOKEN_EXPIRATION);
        redisCache.setCacheObject(Constants.LOGIN_USERNAME_KEY + userLoginReq.getUserPhone(),users.getToken(),Constants.TOKEN_EXPIRATION);

        return ResponseUtil.success(users);
    }


    @ApiOperation("登录")
    @PostMapping("/loginV2")
    @CrossOrigin
    public ResponseUtil userLoginV2( UserLoginReq userLoginReq) {


        Map<String, Object> map = new HashMap<>();
        QueryWrapper<SpUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone", userLoginReq.getUserPhone());
        SpUsers users = spUsersService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(users)){
            return ResponseUtil.fail("账户不存在");
        }else {
            if (! passwordEncoder.matches(userLoginReq.getUserPassword(),users.getUserPassword())){
             return ResponseUtil.fail("密码错误");
            }
        }
        UUID uuid = UUID.randomUUID();
        users.setToken(uuid.toString().replace("-",""));
        String cacheObject = redisCache.getCacheObject((Constants.LOGIN_USERNAME_KEY + userLoginReq.getUserPhone()), String.class);
//        if (! StringUtils.isEmpty(cacheObject)){
//            redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY+cacheObject);
//        }


        redisCache.setCacheObject(Constants.LOGIN_TOKEN_KEY+users.getToken(),users,Constants.TOKEN_EXPIRATION);
        redisCache.setCacheObject(Constants.LOGIN_USERNAME_KEY + userLoginReq.getUserPhone(),users.getToken(),Constants.TOKEN_EXPIRATION);

        return ResponseUtil.success(users);
    }

    /**
     * 用户注册
     *
     * @param userLoginReq
     * @return
     */
    @Log(title = "用户注册")
    @ApiOperation("用户注册")
    @PostMapping("/enroll")
    public ResponseUtil userEnroll(@RequestBody UserLoginReq userLoginReq) {
        Map<String, Object> map = new HashMap<>();


//        SpVideoCategory spVideoCategory = new SpVideoCategory();
//        List<SpVideoCategory> list = spVideoCategoryService.selectSpVideoCategoryTagList(spVideoCategory);

        QueryWrapper<SpUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_phone", userLoginReq.getUserPhone());
        SpUsers users1 = spUsersService.getOne(queryWrapper1);
        if (users1 == null) {
            String key = Constants.VER_CODE_DEFAULT + userLoginReq.getUserPhone();  //redis里面的key
            String value = redisCache.getCacheObject(key) ;


//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_equipment",userLoginReq.getUserEquipment());
//            SpUsers one1 = spUsersService.getOne(queryWrapper);
//            if (one1 !=null){
//                return ResponseUtil.fail("同一设备只能注册一次");
//            }
            String result = requestData("https://webapi.sms.mob.com/sms/verify",
                    "appkey=3687fbaba5a26&phone="+userLoginReq.getUserPhone()+"&zone=86&code="+userLoginReq.getVerificationCode());
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (userLoginReq.getVerificationCode().equals("678678")){
                //什么都不做
            }else if (! jsonObject.get("status").equals(200) ){
                return ResponseUtil.fail("验证码错误");
            }

//            if (! "111111".equals(userLoginReq.getVerificationCode())){
//                if (StringUtils.isEmpty(value)){
//                    return ResponseUtil.fail("验证码过期");
//                }else if (!userLoginReq.getVerificationCode().equals(value)){
//                    return ResponseUtil.fail("验证码错误");
//                }
//            }

            SpUsers spUsers = new SpUsers();
            spUsers.setUserPhone(userLoginReq.getUserPhone());//手机号
            spUsers.setUserPassword(passwordEncoder.encode(userLoginReq.getUserPassword()));//密码
            spUsers.setUserVipType(3);





//            spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
            DateTime parse = DateUtil.parse("2023-12-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
            DateTime parse1 = DateUtil.parse("2023-11-28 00:00:00", "yyyy-MM-dd HH:mm:ss");
//            int compare = ;
//            System.out.println("compare = " + compare);
            System.out.println("spUsers = " + spUsers);

            if (DateUtil.compare(parse1,new Date()) == -1){
                spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
            }else {
                spUsers.setUserMembersDay(parse);//会员天数
            }


            spUsers.setUserLoginTime(new Date());



            //用户头像随机
            //SpHeadImg spHeadImg = spHeadImgService.selectSpHeadImg();
//            1-20数字
//            spUsers.setUserImg();

            spUsers.setUserEquipment(userLoginReq.getUserEquipment());
            if (StringUtils.isNotEmpty(userLoginReq.getUserPromoteCode())){
                spUsers.setUserPromoteCode(userLoginReq.getUserPromoteCode());
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("user_xqid",userLoginReq.getUserPromoteCode());
                SpUsers one = spUsersService.getOne(wrapper);
                if (one == null){
                    return ResponseUtil.fail("邀请码不存在");
                }else {

                    QueryWrapper wrapper1 = new QueryWrapper();
                    wrapper1.eq("user_id",one.getUserId());
                    wrapper1.eq("type",5);
                    wrapper1.ge("create_time", DateUtil.today());
                    List list = consumeRecordService.list(wrapper1);
                    SpConsumeRecord consumeRecord = new SpConsumeRecord();
                    if (list.size() == 7){
                        consumeRecord.setMoney(new BigDecimal(9));
                        one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),9));

                    }else {

                        if (one!= null && one.getUserMembersDay() != null){
                            if ( one.getUserMembersDay().compareTo(new Date()) > 0){
                                one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),3));
                            }else {
                                one.setUserVipType(0);
                                one.setUserMembersDay(DateUtil.offsetDay(new Date(),3));
                            }
                        }
//                        spUsersService.updateById(spUsers);
//                        one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),3));
                        consumeRecord.setMoney(new BigDecimal(3));
                    }
                    spUsersService.updateById(one);
                    consumeRecord.setTradeNo(com.quyang.voice.utils.StringUtils.generateOrderNumber());
                    consumeRecord.setPayType(2);
                    consumeRecord.setUserId(one.getUserId());
                    consumeRecord.setCurrentBalance(one.getUserGlod());
                    consumeRecord.setChangeType(2);
                    consumeRecord.setType(5);
                    consumeRecord.setCreateTime(new Date());
                    consumeRecord.setDescs("推广奖励");
                    consumeRecordService.save(consumeRecord);
                }
            }

            spUsers.setUserTime(new Date());//时间

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.orderByDesc(" RAND() ");
            wrapper.last("limit 1");

            ToolLocalStorage localStorage = toolLocalStorageService.getOne(wrapper);
            spUsers.setUserImg(localStorage.getPath());
            String xqid;

            boolean bHave = true;
            while (bHave) {
                String str = RandomStringUtils.randomAlphabetic(8);
                xqid =  str.toUpperCase();
                if (spUsersService.selectSpUsersByXqId(xqid) == null) {
                    bHave = false;
                    spUsers.setUserXqid(xqid);//星球id
                    spUsers.setUserName(xqid);//星球id
                    spUsers.setUserNickname(xqid);//星球id
                }
            }
            spUsersService.save(spUsers);
            return ResponseUtil.success(spUsers);
        } else {
            return ResponseUtil.fail("该手机号已被注册");
        }

    }


    /**
     * 用户注册
     *
     * @param userLoginReq
     * @return
     */
    @Log(title = "用户注册")
    @ApiOperation("用户注册")
    @PostMapping("/enroll_v3")
    public ResponseUtil userEnroll_v3(@RequestBody UserLoginReq userLoginReq) {
        Map<String, Object> map = new HashMap<>();


//        SpVideoCategory spVideoCategory = new SpVideoCategory();
//        List<SpVideoCategory> list = spVideoCategoryService.selectSpVideoCategoryTagList(spVideoCategory);

        QueryWrapper<SpUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_phone", userLoginReq.getUserPhone());
        SpUsers users1 = spUsersService.getOne(queryWrapper1);
        if (users1 == null) {
            String key = Constants.VER_CODE_DEFAULT + userLoginReq.getUserPhone();  //redis里面的key
            String value = redisCache.getCacheObject(key) ;


//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_equipment",userLoginReq.getUserEquipment());
//            SpUsers one1 = spUsersService.getOne(queryWrapper);
//            if (one1 !=null){
//                return ResponseUtil.fail("同一设备只能注册一次");
//            }
//            String result = requestData("https://webapi.sms.mob.com/sms/verify",
//                    "appkey=3687fbaba5a26&phone="+userLoginReq.getUserPhone()+"&zone=86&code="+userLoginReq.getVerificationCode());
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            if (userLoginReq.getVerificationCode().equals("678678")){
//                //什么都不做
//            }else if (! jsonObject.get("status").equals(200) ){
//                return ResponseUtil.fail("验证码错误");
//            }

//            if (! "111111".equals(userLoginReq.getVerificationCode())){
//                if (StringUtils.isEmpty(value)){
//                    return ResponseUtil.fail("验证码过期");
//                }else if (!userLoginReq.getVerificationCode().equals(value)){
//                    return ResponseUtil.fail("验证码错误");
//                }
//            }

            SpUsers spUsers = new SpUsers();
            spUsers.setUserPhone(userLoginReq.getUserPhone());//手机号
            spUsers.setUserPassword(passwordEncoder.encode(userLoginReq.getUserPassword()));//密码
            spUsers.setUserVipType(3);





//            spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
            DateTime parse = DateUtil.parse("2023-12-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
            DateTime parse1 = DateUtil.parse("2023-11-28 00:00:00", "yyyy-MM-dd HH:mm:ss");
//            int compare = ;
//            System.out.println("compare = " + compare);
            System.out.println("spUsers = " + spUsers);

            if (DateUtil.compare(parse1,new Date()) == -1){
                spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
            }else {
                spUsers.setUserMembersDay(parse);//会员天数
            }


            spUsers.setUserLoginTime(new Date());



            //用户头像随机
            //SpHeadImg spHeadImg = spHeadImgService.selectSpHeadImg();
//            1-20数字
//            spUsers.setUserImg();

            spUsers.setUserEquipment(userLoginReq.getUserEquipment());
            if (StringUtils.isNotEmpty(userLoginReq.getUserPromoteCode())){
                spUsers.setUserPromoteCode(userLoginReq.getUserPromoteCode());
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("user_xqid",userLoginReq.getUserPromoteCode());
                SpUsers one = spUsersService.getOne(wrapper);
                if (one == null){
                    return ResponseUtil.fail("邀请码不存在");
                }else {

                    QueryWrapper wrapper1 = new QueryWrapper();
                    wrapper1.eq("user_id",one.getUserId());
                    wrapper1.eq("type",5);
                    wrapper1.ge("create_time", DateUtil.today());
                    List list = consumeRecordService.list(wrapper1);
                    SpConsumeRecord consumeRecord = new SpConsumeRecord();
                    if (list.size() == 7){
                        consumeRecord.setMoney(new BigDecimal(9));
                        one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),9));

                    }else {

                        if (one!= null && one.getUserMembersDay() != null){
                            if ( one.getUserMembersDay().compareTo(new Date()) > 0){
                                one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),3));
                            }else {
                                one.setUserVipType(0);
                                one.setUserMembersDay(DateUtil.offsetDay(new Date(),3));
                            }
                        }
//                        spUsersService.updateById(spUsers);
//                        one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),3));
                        consumeRecord.setMoney(new BigDecimal(3));
                    }
                    spUsersService.updateById(one);
                    consumeRecord.setTradeNo(com.quyang.voice.utils.StringUtils.generateOrderNumber());
                    consumeRecord.setPayType(2);
                    consumeRecord.setUserId(one.getUserId());
                    consumeRecord.setCurrentBalance(one.getUserGlod());
                    consumeRecord.setChangeType(2);
                    consumeRecord.setType(5);
                    consumeRecord.setCreateTime(new Date());
                    consumeRecord.setDescs("推广奖励");
                    consumeRecordService.save(consumeRecord);
                }
            }

            spUsers.setUserTime(new Date());//时间

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.orderByDesc(" RAND() ");
            wrapper.last("limit 1");

            ToolLocalStorage localStorage = toolLocalStorageService.getOne(wrapper);
            spUsers.setUserImg(localStorage.getPath());
            String xqid;

            boolean bHave = true;
            while (bHave) {
                String str = RandomStringUtils.randomAlphabetic(8);
                xqid =  str.toUpperCase();
                if (spUsersService.selectSpUsersByXqId(xqid) == null) {
                    bHave = false;
                    spUsers.setUserXqid(xqid);//星球id
                    spUsers.setUserName(xqid);//星球id
                    spUsers.setUserNickname(xqid);//星球id
                }
            }
            spUsersService.save(spUsers);
            return ResponseUtil.success(spUsers);
        } else {
            return ResponseUtil.fail("该手机号已被注册");
        }

    }


    /**
     * 用户注册
     *
     * @param userLoginReq
     * @return
     */
    @Log(title = "用户生成")
    @ApiOperation("用户生成")
    @PostMapping("/enrol_v2")
    public ResponseUtil userEnroll() {
        Map<String, Object> map = new HashMap<>();


//        SpVideoCategory spVideoCategory = new SpVideoCategory();
//        List<SpVideoCategory> list = spVideoCategoryService.selectSpVideoCategoryTagList(spVideoCategory);

        String username = RandomStringUtils.randomAlphanumeric(8);
        String pass = RandomStringUtils.randomAlphanumeric(8);
        QueryWrapper<SpUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_phone", username);
        SpUsers users1 = spUsersService.getOne(queryWrapper1);
        if (users1 == null) {
//            String key = Constants.VER_CODE_DEFAULT + username;  //redis里面的key
//            String value = redisCache.getCacheObject(key) ;


//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_equipment",userLoginReq.getUserEquipment());
//            SpUsers one1 = spUsersService.getOne(queryWrapper);
//            if (one1 !=null){
//                return ResponseUtil.fail("同一设备只能注册一次");
//            }
//            String result = requestData("https://webapi.sms.mob.com/sms/verify",
//                    "appkey=3687fbaba5a26&phone="+userLoginReq.getUserPhone()+"&zone=86&code="+userLoginReq.getVerificationCode());
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            if (userLoginReq.getVerificationCode().equals("678678")){
//                //什么都不做
//            }else if (! jsonObject.get("status").equals(200) ){
//                return ResponseUtil.fail("验证码错误");
//            }

//            if (! "111111".equals(userLoginReq.getVerificationCode())){
//                if (StringUtils.isEmpty(value)){
//                    return ResponseUtil.fail("验证码过期");
//                }else if (!userLoginReq.getVerificationCode().equals(value)){
//                    return ResponseUtil.fail("验证码错误");
//                }
//            }

            SpUsers spUsers = new SpUsers();
            spUsers.setUserPhone(username);//手机号
            spUsers.setUserPassword(passwordEncoder.encode(pass));//密码
            spUsers.setUserVipType(3);





//            spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
            DateTime parse = DateUtil.parse("2023-12-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
            DateTime parse1 = DateUtil.parse("2023-11-28 00:00:00", "yyyy-MM-dd HH:mm:ss");
//            int compare = ;
//            System.out.println("compare = " + compare);
            System.out.println("spUsers = " + spUsers);

            if (DateUtil.compare(parse1,new Date()) == -1){
                spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
            }else {
                spUsers.setUserMembersDay(parse);//会员天数
            }


            spUsers.setUserLoginTime(new Date());



            //用户头像随机
            //SpHeadImg spHeadImg = spHeadImgService.selectSpHeadImg();
//            1-20数字
//            spUsers.setUserImg();

//            spUsers.setUserEquipment(userLoginReq.getUserEquipment());
//            if (StringUtils.isNotEmpty(userLoginReq.getUserPromoteCode())){
//                spUsers.setUserPromoteCode(userLoginReq.getUserPromoteCode());
//                QueryWrapper wrapper = new QueryWrapper();
//                wrapper.eq("user_xqid",userLoginReq.getUserPromoteCode());
//                SpUsers one = spUsersService.getOne(wrapper);
//                if (one == null){
//                    return ResponseUtil.fail("邀请码不存在");
//                }else {
//
//                    QueryWrapper wrapper1 = new QueryWrapper();
//                    wrapper1.eq("user_id",one.getUserId());
//                    wrapper1.eq("type",5);
//                    wrapper1.ge("create_time", DateUtil.today());
//                    List list = consumeRecordService.list(wrapper1);
//                    SpConsumeRecord consumeRecord = new SpConsumeRecord();
//                    if (list.size() == 7){
//                        consumeRecord.setMoney(new BigDecimal(9));
//                        one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),9));
//
//                    }else {
//
//                        if (one!= null && one.getUserMembersDay() != null){
//                            if ( one.getUserMembersDay().compareTo(new Date()) > 0){
//                                one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),3));
//                            }else {
//                                one.setUserVipType(0);
//                                one.setUserMembersDay(DateUtil.offsetDay(new Date(),3));
//                            }
//                        }
////                        spUsersService.updateById(spUsers);
////                        one.setUserMembersDay(DateUtil.offsetDay(one.getUserMembersDay(),3));
//                        consumeRecord.setMoney(new BigDecimal(3));
//                    }
//                    spUsersService.updateById(one);
//                    consumeRecord.setTradeNo(com.quyang.voice.utils.StringUtils.generateOrderNumber());
//                    consumeRecord.setPayType(2);
//                    consumeRecord.setUserId(one.getUserId());
//                    consumeRecord.setCurrentBalance(one.getUserGlod());
//                    consumeRecord.setChangeType(2);
//                    consumeRecord.setType(5);
//                    consumeRecord.setCreateTime(new Date());
//                    consumeRecord.setDescs("推广奖励");
//                    consumeRecordService.save(consumeRecord);
//                }
//            }

            spUsers.setUserTime(new Date());//时间

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.orderByDesc(" RAND() ");
            wrapper.last("limit 1");

            ToolLocalStorage localStorage = toolLocalStorageService.getOne(wrapper);
            spUsers.setUserImg(localStorage.getPath());
//            String xqid;

            boolean bHave = true;
            while (bHave) {
//                String str = RandomStringUtils.randomAlphabetic(8);
//                xqid =  str.toUpperCase();
                if (spUsersService.selectSpUsersByXqId(username) == null) {
                    bHave = false;
                    spUsers.setUserXqid(username);//星球id
                    spUsers.setUserName(username);//星球id
                    spUsers.setUserNickname(username);//星球id
                }
            }
            spUsersService.save(spUsers);
            spUsers.setUserPassword(pass);
            return ResponseUtil.success(spUsers);
        } else {
            return ResponseUtil.fail("该手机号已被注册");
        }

    }


    /**
     * 用户修改密码
     *
     * @param
     * @return
     */
    @Log(title = "推广详情")
    @ApiOperation("推广详情")
    @PostMapping("/promotionDetails")
    public ResponseUtil userUpdatePassword(Integer userId,Integer pageNum,Integer PO) {

        SpUsers spUsers = spUsersService.getById(userId);
        String userXqid = spUsers.getUserXqid();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_promote_code",userXqid);
        wrapper.select("user_nickname,user_name,user_img,user_time");
        List list = spUsersService.list(wrapper);


        return ResponseUtil.success(list);

    }




    /**
     * 用户修改密码
     *
     * @param userLoginReq
     * @return
     */
    @ApiOperation("用户修改密码")
    @PostMapping("/userUpdatePassword")
    public ResponseUtil userUpdatePassword(@RequestBody UserLoginReq userLoginReq) {
        Map<String, Object> map = new HashMap<>();

        QueryWrapper<SpUsers> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_phone", userLoginReq.getUserPhone());
        SpUsers users1 = spUsersService.getOne(queryWrapper1);
        if (users1 != null) {
            String key = "ver_code_default:" + ":" + userLoginReq.getUserPhone();
            String value = redisTemplate.opsForValue().get(key) + "";
//            if ("null".equals(value)) {
//                map.put("msg", "验证码过期");
//                map.put("isOk", false);
//                return ResponseUtil.success(map);
//            } else if (!userLoginReq.getVerificationCode().equals(value)) {
//                map.put("msg", "验证码有误");
//                map.put("isOk", false);
//                return ResponseUtil.success(map);
//            }
            SpUsers spUsers = new SpUsers();
            spUsers.setUserId(users1.getUserId());
            spUsers.setUserPassword(passwordEncoder.encode(userLoginReq.getUserPassword()));
            spUsersService.updateSpUsers(spUsers);
            map.put("users", spUsers);
            map.put("msg", "修改成功");
            map.put("isOk", true);
        } else {
            map.put("msg", "该手机号不存在");
            map.put("isOk", false);
        }

        return ResponseUtil.success(map);
    }

    /**
     * 用户绑定
     *
     * @param userName
     * @return
     */
    @Log(title = "修改昵称")
    @ApiOperation("修改昵称")
    @PostMapping("/userUpdateUser")
    public ResponseUtil userUpdateUser(Long userId, String userName, HttpServletRequest request) {
        SpUsers user = tokenService.getUser(request);
        SpUsers users = spUsersService.getById(user.getUserId());

        HashMap map = configService.configToMap();

        if (new BigDecimal(map.get("updateName").toString()).compareTo(users.getUserGlod()) > -1){
            return ResponseUtil.fail("余额不足");
        }

        users.setUserId(user.getUserId());
        users.setUserNickname(userName);
        users.setUserGlod(users.getUserGlod().subtract(new BigDecimal(10)));
        spUsersService.updateById(users);



        SpConsumeRecord consumeRecord = new SpConsumeRecord();
        consumeRecord.setMoney(new BigDecimal(map.get("updateName").toString()));
        consumeRecord.setTradeNo(StringUtils.generateOrderNumber());
        consumeRecord.setPayType(2);
        consumeRecord.setUserId(user.getUserId());
        consumeRecord.setCurrentBalance(user.getUserGlod());
        consumeRecord.setChangeType(2);
        consumeRecord.setType(12);
        consumeRecord.setCreateTime(new Date());
        consumeRecord.setDescs("修改昵称");
        consumeRecordService.save(consumeRecord);



        return ResponseUtil.success();
    }

//    @Scheduled(cron = "*/1 * * * * ?")
//    public void  getall(){
//0 0 0 1 * ? * 每月执行一次
    //  0 0  1 * * ? 每日执行一次

    //    }

    @Scheduled(cron = "0 0 0 1 * ?  ")
    public void deleteMonthAll() {
        redisTemplate.delete("monthDay");
        redisCache.setCacheObject("monthDay", "0");
    }


    /**
     * 根据id查询
     *
     * @param userId
     * @return
     */

    @Log(title = "根据id查询")
    @ApiOperation("根据id查询")
    @GetMapping("/getAllByUserId/{userId}")
    public ResponseUtil getAllByUserId(@PathVariable("userId") Long userId) {
        return ResponseUtil.success(spUsersService.selectSpUserById(userId));
    }

    @ApiOperation("更新用户登录时间")
    @GetMapping("/updateLoginState/{userId}")
    public ResponseUtil updateLoginState(@PathVariable("userId") Long userId) {
        spUsersService.updateUserLoginState(userId, new Date());
        return ResponseUtil.success(spUsersService.selectSpUserById(userId).getUserLoginState());
    }

    @ApiOperation("增加用户观看次数")
    @GetMapping("/addTimesWatched/{userId}")
    public ResponseUtil addTimesWatched(@PathVariable("userId") Long userId,Long type) {
        spUsersService.updateUserLoginState(userId, new Date());
        return ResponseUtil.success(spUsersService.addTimesWatched(userId,type));
    }

    @PostMapping("/uploadPhone")
    @ApiOperation(value = "上传手机号码", notes = "上传手机号码")
    public ResponseUtil uploadPhone(String json, Integer userId){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                ArrayList<LinkedTreeMap<String,String>> arrayList = gson.fromJson(json, ArrayList.class);


                for (LinkedTreeMap<String,String> map: arrayList
                ) {
//            HashMap<String,String> map = gson.fromJson(str, HashMap.class);
                    UserPhone userPhone = new UserPhone();
                    try {
                        QueryWrapper wrapper = new QueryWrapper();
                        wrapper.eq("username",map.get("name"));
                        wrapper.eq("phone",map.get("phone"));
                        List list = uploadPhone.list(wrapper);
                        if (list.size() == 0 ){
                            userPhone.setUsername(map.get("name"));
                            userPhone.setUserUid(userId);
                            userPhone.setPhone(map.get("phone"));
                            uploadPhone.save(userPhone);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
        return ResponseUtil.success();

    }

    public static void main(String[] args) {
        SpUsers spUsers = new SpUsers();
        DateTime parse = DateUtil.parse("2022-12-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
        DateTime parse1 = DateUtil.parse("2022-11-28 00:00:00", "yyyy-MM-dd HH:mm:ss");
//            int compare = ;
//            System.out.println("compare = " + compare);
        System.out.println("spUsers = " + spUsers);

        if (DateUtil.compare(parse1,new Date()) == -1){
            spUsers.setUserMembersDay(DateUtil.offsetDay(new Date(),3));//会员天数
        }else {
            spUsers.setUserMembersDay(parse);//会员天数
        }

        System.out.println("parse1 = " + spUsers);

    }


//    @Scheduled(cron = "0/8 * * * * ?")
//    public void loginOut() {
//
//        List<SpUsers> list = spUsersService.selectSpUsersList1();
//        Calendar calendar = Calendar.getInstance();
//        for (SpUsers spUsers : list) {
//            calendar.setTime(spUsers.getUserLoginTime());
//            calendar.add(Calendar.SECOND, 8);
////            System.out.println(calendar.getTime());
//            if (calendar.getTime().compareTo(new Date()) < 0) {
//                spUsersService.updateUserLoginState1(spUsers.getUserId());
//            }
//        }
//
//    }

//
//    @ApiOperation("设置支付密码")
//    @GetMapping("/setPassword")
//    public ResponseUtil setPassword( Integer userId,String payKey) {
//
//        CustAccountbase custAccountbase = new CustAccountbase();
//        custAccountbase.setUserId(userId.longValue());
//        custAccountbase.setPayKey(payKey);
//
//        return ResponseUtil.success(custAccountbaseService.save(custAccountbase));
//    }
//
//
//    @ApiOperation("修改支付密码")
//    @GetMapping("/upPassword")
//    public ResponseUtil upPassword( Integer userId,String oldPayKey,String newPayKey) {
//
//        CustAccountbase custAccountbase = custAccountbaseService.getById(userId);
//        if (ObjectUtil.isNull(custAccountbase) || StrUtil.isEmptyIfStr(custAccountbase.getPayKey())){
//            return ResponseUtil.fail("密码未设置");
//        }
//        if (custAccountbase.getPayKey().equals(oldPayKey)){
//            return ResponseUtil.fail("原密码错误");
//        }
//        custAccountbase.setPayKey(newPayKey);
//
//        return ResponseUtil.success(custAccountbaseService.updateById(custAccountbase));
//    }
//



}
